package com.cardone.common.mapper;

import java.io.StringReader;
import java.io.StringWriter;
import java.util.Collection;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlAnyElement;
import javax.xml.namespace.QName;

import lombok.NonNull;
import lombok.experimental.ExtensionMethod;

import org.apache.commons.codec.CharEncoding;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.converter.HttpMessageConversionException;

import com.google.common.base.Throwables;

/**
 * 使用Jaxb2.0实现XML<->Java Object的Mapper. 在创建时需要设定所有需要序列化的Root对象的Class.
 * 特别支持Root对象是Collection的情形.
 * 
 * @author yaoht
 */
@ExtensionMethod({ IOUtils.class })
public class JaxbMapper {
	/**
	 * 封装Root Element 是 Collection的情况.
	 */
	public static class CollectionWrapper {
		@XmlAnyElement
		private Collection<?> collection;
	}

	private static ConcurrentMap<Class<?>, JAXBContext> jaxbContexts = new ConcurrentHashMap<Class<?>, JAXBContext>();

	/**
	 * 创建Marshaller并设定encoding(可为null). 线程不安全，需要每次创建或pooling。
	 */
	public static Marshaller createMarshaller(@NonNull final Class<?> clazz, final String encoding) {
		try {
			final JAXBContext jaxbContext = JaxbMapper.getJaxbContext(clazz);

			final Marshaller marshaller = jaxbContext.createMarshaller();

			marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

			String newEncoding = StringUtils.defaultIfBlank(encoding, CharEncoding.UTF_8);

			marshaller.setProperty(Marshaller.JAXB_ENCODING, newEncoding);

			return marshaller;
		} catch (final JAXBException e) {
			throw new RuntimeException(Throwables.getStackTraceAsString(e));
		}
	}

	/**
	 * 创建UnMarshaller. 线程不安全，需要每次创建或pooling。
	 */
	public static Unmarshaller createUnmarshaller(@NonNull final Class<?> clazz) {
		try {
			final JAXBContext jaxbContext = JaxbMapper.getJaxbContext(clazz);

			return jaxbContext.createUnmarshaller();
		} catch (final JAXBException e) {
			throw new RuntimeException(Throwables.getStackTraceAsString(e));
		}
	}

	/**
	 * Xml->Java Object.
	 */
	@SuppressWarnings("unchecked")
	public static <T> T fromXml(@NonNull final String xml, @NonNull final Class<T> clazz) {
		StringReader reader = null;

		try {
			reader = new StringReader(xml);

			return (T) JaxbMapper.createUnmarshaller(clazz).unmarshal(reader);
		} catch (final JAXBException e) {
			throw new RuntimeException(Throwables.getStackTraceAsString(e));
		} finally {
			reader.closeQuietly();
		}
	}

	private static JAXBContext getJaxbContext(@NonNull final Class<?> clazz) {
		JAXBContext jaxbContext = JaxbMapper.jaxbContexts.get(clazz);

		if (jaxbContext != null) {
			return jaxbContext;
		}

		try {
			jaxbContext = JAXBContext.newInstance(clazz, CollectionWrapper.class);

			final JAXBContext newJAXBContext = JaxbMapper.jaxbContexts.putIfAbsent(clazz, jaxbContext);

			if (newJAXBContext != null) {
				return newJAXBContext;
			}

			return jaxbContext;
		} catch (final JAXBException ex) {
			throw new HttpMessageConversionException("Could not instantiate JAXBContext for class [" + clazz + "]: " + ex.getMessage(),
			        ex);
		}
	}

	/**
	 * Java Collection->Xml without encoding, 特别支持Root Element是Collection的情形.
	 */
	public static String toXml(@NonNull final Collection<?> root, @NonNull final String rootName, @NonNull final Class<?> clazz) {
		return JaxbMapper.toXml(root, rootName, clazz, null);
	}

	/**
	 * Java Collection->Xml with encoding, 特别支持Root Element是Collection的情形.
	 */
	public static String toXml(@NonNull final Collection<?> root, @NonNull final String rootName, @NonNull final Class<?> clazz,
	        final String encoding) {
		StringWriter writer = null;

		try {
			final CollectionWrapper wrapper = new CollectionWrapper();

			wrapper.collection = root;

			final JAXBElement<CollectionWrapper> wrapperElement = new JAXBElement<CollectionWrapper>(new QName(rootName),
			        CollectionWrapper.class, wrapper);

			writer = new StringWriter();

			JaxbMapper.createMarshaller(clazz, encoding).marshal(wrapperElement, writer);

			return writer.toString();
		} catch (final JAXBException e) {
			throw new RuntimeException(Throwables.getStackTraceAsString(e));
		} finally {
			writer.closeQuietly();
		}
	}

	/**
	 * Java Object->Xml without encoding.
	 */
	public static String toXml(@NonNull final Object root) {
		final Class<?> clazz = root.getClass();

		return JaxbMapper.toXml(root, clazz, null);
	}

	/**
	 * Java Object->Xml with encoding.
	 */
	public static String toXml(@NonNull final Object root, @NonNull final Class<?> clazz, final String encoding) {
		StringWriter writer = null;

		try {
			writer = new StringWriter();

			JaxbMapper.createMarshaller(clazz, encoding).marshal(root, writer);

			return writer.toString();
		} catch (final JAXBException e) {
			throw new RuntimeException(Throwables.getStackTraceAsString(e));
		} finally {
			writer.closeQuietly();
		}
	}

	/**
	 * Java Object->Xml with encoding.
	 */
	public static String toXml(@NonNull final Object root, @NonNull final String encoding) {
		final Class<?> clazz = root.getClass();

		return JaxbMapper.toXml(root, clazz, encoding);
	}
}
